<?php
/**
 * Created by PhpStorm.
 * User: prg
 * Date: 2017/2/27
 * Time: 20:49
 */

//管理员删除普通用户功能
require_once 'db.php';
require_once 'response.php';

header('content-type:text/html;charset:utf-8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');

$username = isset($_POST['username']) ? $_POST['username'] : '';

if(empty($username)) {
    Response::show(401,'数据不合法');
}

//连接数据库
try {
    $connect = Db::getInstance()->connect();
} catch (Exception $e) {
//    $e->getMessage();
    return Response::show(403,'数据库连接失败',$e->getMessage());
}

//查询用户名对应的用户级别，如果为普通用户就删除，如果为管理员用户就显示权限不足
$sql = "SELECT user_type FROM user WHERE username=?";

$mysqli_stmt = $connect->prepare($sql);
$mysqli_stmt->bind_param('s',$username);
$type = '';
$data = array(
    'IsDelete' => false,
);

if($mysqli_stmt->execute()) {
    $mysqli_stmt->bind_result($type);
    if($mysqli_stmt->fetch()) {
        if($type == 0) {
            //管理员级别的用户不给删除
            return Response::show(402,'权限不足,无法删除',$data);
        } else {
            //普通级别的用户进行删除

            //将预处理语句结果集释放并关闭，不关闭就执行不了下一条sql语句了
            $mysqli_stmt->free_result();
            $mysqli_stmt->close();

            $sql = "DELETE FROM user WHERE username='{$username}'";
            $res = $connect->query($sql);
            if($res) {
                $data['IsDelete'] = true;
                return Response::show(200,'用户删除成功',$data);
            } else {
//                echo $connect->error;
                return Response::show(405,'用户删除失败,sql语句执行失败',$data);
            }
        }
    } else {
        return Response::show('400','用户名传入错误,找不到这样的用户名',$data);
    }
} else {
    return Response::show('404','删除失败,服务器没响应',$data);
}

//释放结果集
//$mysqli_stmt->free_result();
////关闭预处理语句
//$mysqli_stmt->close();
////关闭连接
//$connect->close();




